import request from '../api/request'
import { SET_USER, GO_SHERD } from '../actions/actions'

// 生产环境
export const baseURL = 'http://wx.camluni.com'
// export const baseURL = 'http://suosuo.hippovip.com:3000'
// export const baseURL = 'http://129.204.77.105:3000'

// 开发环境
// export const baseURL = 'http://gxspp.nat300.top'
// export const baseURL = 'http://127.0.0.1:7070'
// export const baseURL = 'http://192.168.31.179:7070'

// 卡莫生产环境
export const appid = 'wxbc2631875fcdbfb3'
export const appsecret = 'b27fa84e67ec25d4469ed12e2f54a23a'

// // 生产环境
// export const appid = 'wx0cf6e1b038363a06'
// export const appsecret = '38a563637a7fcaf0e672bbfea26c8b47'

// 开发环境
// export const appid = "wx7495a9020ba761d7";
// export const appSecret = "c18b55a9b627c9c5ba9de47a4f5aac98";

export const getImgUrl = (url) => baseURL + url

export const requstPromise = (res) => {
  return new Promise((resolve, reject) => {
    if (res) {
      resolve(res)
    } else {
      reject(res)
    }
  }).catch(error => {
    console.log(error)
  })

}



export const getUrl = () => {
  let url = window.location.search;// 得到url问号后面拼接的参数  ?id=12345&a=b
  let obj = {};// 创建一个Object
  let reg = /[?&][^?&]+=[^?&]+/g;// 正则匹配 ?&开始 =拼接  非?&结束  的参数
  let arr = url.match(reg);// match() 方法可在字符串内检索指定的值，或找到一个或多个正则表达式的匹配。
  // arr数组形式 ['?id=12345','&a=b']
  if (arr) {
    arr.forEach((item) => {
      /**
       * tempArr数组    ['id','12345']和['a','b']
      * 第一个是key，第二个是value
      * */
      let tempArr = item.substring(1).split('=');
      let key = decodeURIComponent(tempArr[0]);
      let val = decodeURIComponent(tempArr[1]);
      obj[key] = val;
    });
  }
  return obj;
};

export const getCode = () => {
  localStorage.removeItem('user')
  console.log(window)
  let inviter = getUrl().inviter
  let url
  if (inviter) {
    console.log(inviter)
    alert(inviter)
    alert(`${window.location.origin}${window.location.pathname}?inviter=${inviter}`)
    url = `${window.location.origin}${window.location.pathname}?inviter=${inviter}`
  } else {
    url = `${window.location.origin}${window.location.pathname}`
  }
  let redirectUrl = encodeURIComponent(url)
  window.location.href = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appid}&redirect_uri=${redirectUrl}&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect`;
}



export const getUserInfo = (dispatch, option) => {
  request.getUserInfo(option).then(res => {
    console.log(res)
    dispatch({
      type: SET_USER,
      data: res.data
    })
  })
}

export const openSherd = (dispatch) => {
  dispatch({
    type: GO_SHERD,
    data: true
  })
}

export const closeSherd = (dispatch) => {
  dispatch({
    type: GO_SHERD,
    data: false
  })
}

export const hideSpinner = () => {
  var spinner = document.getElementById("spinner")
  spinner.style.display = "none"
}

export const share = (openid, dispatch) => {
  request.share({ openid: openid }).then(res => {
    getUserInfo(dispatch, { openid })
    alert(res.message)
  })
}

export const setSherd = (openid, dispatch) => {
  let url = window.location.href.split('#')[0]
  request.getWxConfig({ url }).then(res => {
    console.log(res)
    window.wx.config({
      debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
      appId: appid, // 必填，公众号的唯一标识
      timestamp: res.data.timestamp, // 必填，生成签名的时间戳
      nonceStr: res.data.noncestr, // 必填，生成签名的随机串
      signature: res.data.signature,// 必填，签名
      jsApiList: ['onMenuShareAppMessage', 'onMenuShareTimeline'] // 必填，需要使用的JS接口列表
    });
    window.wx.ready(() => {   //需在用户可能点击分享按钮前就先调用
      window.wx.onMenuShareAppMessage({
        title: '想来一场刺激的头脑挑战吗？', // 分享标题
        desc: `点击链接开黑！`, // 分享描述
        link: `${url}?inviter=${openid}`, // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
        imgUrl: `${baseURL}/images/fxtx.jpg`, // 分享图标
        success: () => {
          // 用户点击了分享后执行的回调函数
          share(openid, dispatch)
        }
      })
      //分享到朋友圈
      window.wx.onMenuShareTimeline({
        title: `比一比谁才是真正的「脑力王者」`, // 分享标题
        desc: `PK吗老铁？点击链接开黑！`, // 分享描述
        link: `${url}?inviter=${openid}`, // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
        imgUrl: `${baseURL}/images/fxtx.jpg`, // 分享图标
        success: () => {
          // 用户点击了分享后执行的回调函数
          share(openid, dispatch)
        }
      })
      hideSpinner()
    });
  })
}
